package xyz.labmem.main.sys;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUnit;
import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.Data;
import xyz.labmem.main.application.entity.sys.Role;
import xyz.labmem.main.application.entity.sys.RoleValid;
import xyz.labmem.main.application.entity.sys.User;
import xyz.labmem.main.tool.Jackson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 初始化存放的静态变量
 * Created by Lty
 * Created in 10:08 2020-3-6
 */
@Data
public abstract class StaticVariable {

    private static final TransmittableThreadLocal<User> USER = new TransmittableThreadLocal<>();

    public static void saveUser(User user) {
        USER.set(user);
    }

    public static void updateUser(User user) {
        remove();
        USER.set(user);
    }

    public static User getUser() {
        return USER.get();
    }

    public static void remove() {
        USER.remove();
    }

    /**
     * 角色权限
     */
    protected static Map<String, Role> roles;

    /**
     * 默认权限
     */
    protected static Role rolesDef;

    /**
     * 所有权限接口列表
     */
    protected static Map<String, String> RoleValidEntities = new ConcurrentHashMap<>();

    /**
     * 新增权限接口列表，待持续化
     */
    protected static List<RoleValid> NewRoleValidEntities = new ArrayList<>();

    /**
     * 通过key获取静态变量中的权限
     *
     * @param key API的路径+方法
     * @return
     */
    protected static List<String> getRoleList(String key) {
        String role = RoleValidEntities.get(key);
        if (role != null) {
            return Jackson.JsonToObject(role, List.class);
        }
        return null;
    }

    /**
     * ip请求次数
     */
    protected static Map<String, Integer> IpNum = new ConcurrentHashMap<>();

    /**
     * ip缓存
     */
    protected static TimedCache<String, String> IpCache = CacheUtil.newTimedCache(DateUnit.MINUTE.getMillis());

    /**
     * ip黑名单
     */
    protected static TimedCache<String, Boolean> IpBlacklist = CacheUtil.newTimedCache(DateUnit.MINUTE.getMillis() * 5);

}
